import { useEffect, useRef, useState } from "react";
import { ScrollView, View } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import {
  Swiper,
  Image,
  Button,
  FloatingBubble,
  TextEllipsis,
} from "@taroify/core";
import { ArrowUp } from "@taroify/icons";
import StyleModule from "./index.module.scss";

import HeaderSearch from "@/components/HeaderSearch/index";
import Header from "@/components/Header/index";
import GoodsTitle from "@/components/GoodsTitle/index";
import Quotation from "./components/Quotations";
import HomeFooter from "./components/HomeFooter";
import Footer from "@/components/Footer/index";
import { requestPOST } from "@/request";
import useInitStore from "@/hooks/useInitStore";
import { useDispatch, useSelector } from "react-redux";
import { setBusinessCategory } from "@/store/reducers/commonCategory";
import { RootState } from "@/store";
import { setShopInfo, setUserInfo } from "@/store/reducers/userInfo";
import { setBusinessInfo, setHomeShow } from "@/store/reducers/businessInfo";
import { setActive } from "@/store/reducers/tabbar";

export default function Index() {
  const dispatch = useDispatch();

  const businessId = useSelector(
    (state: RootState) => state.business.businessId
  );
  const isHomeShow = useSelector(
    (state: RootState) => state.business.isHomeShow
  );
  const userInfoRedux = useSelector((state: RootState) => {
    state.userInfo.userInfo;
  });
  const shopInfo = useSelector((state: RootState) => state.userInfo.shopInfo);

  const [swiperList, setSwiperList] = useState<
    Array<{ image: string; toUrl: string }>
  >([]);
  const [hotProductList, setHotProductList] = useState<any[]>([]);
  const [newProductList, setNewProductList] = useState<any[]>([]);
  const [bannerImage, setBannerImage] = useState("");
  const [recommendList, setRecommendList] = useState<any[]>([]);
  const [newsList, setNewsList] = useState<any[]>([]);
  const [brands, setBrands] = useState<any[]>([]);
  const isFirstRender = useRef(true);

  useInitStore();

  const initBannerList = () => {
    requestPOST("other/bannerList/1").then((res: any[]) => {
      const result = res.map((item) => ({
        toUrl: item.toUrl,
        image: process.env.TARO_APP_API + item.image,
      }));
      setSwiperList(result);
    });
  };

  const getHotProductList = () => {
    requestPOST(
      businessId && isHomeShow ? "shop/hotCommodity" : "index/hotCommodity",
      {
        businessId: businessId,
        pageNum: 1,
        pageSize: 3,
      }
    ).then((res: any) => {
      setHotProductList(
        res.vos.map((item) => ({
          ...item,
          image: process.env.TARO_APP_API + item.image,
        }))
      );
    });
  };

  const getNewProductList = () => {
    requestPOST(
      businessId && isHomeShow ? "shop/newCommodity" : "index/newCommodity",
      {
        businessId: businessId,
        pageNum: 1,
        pageSize: 10,
      }
    ).then((res: any) => {
      setNewProductList(
        res.vos.map((item) => ({
          ...item,
          image: process.env.TARO_APP_API + item.image,
        }))
      );
    });
  };

  const getBannerImage = () => {
    requestPOST("other/bannerList/2").then((res: any) => {
      setBannerImage(process.env.TARO_APP_API + res[0].image);
    });
  };

  const getRecommendList = () => {
    requestPOST(
      businessId && isHomeShow
        ? "shop/boutiqueCommodity"
        : "index/recommendedClassification",
      {
        businessId: businessId,
        pageNum: 1,
        pageSize: 9,
        isHostMore: 0,
      }
    ).then((res: any) => {
      setRecommendList(
        res.vos.map((item) => ({
          ...item,
          image: process.env.TARO_APP_API + item.image,
        }))
      );
    });
  };

  const getNewsList = () => {
    requestPOST("index/getIndexShipList", {
      pageNum: 1,
      pageSize: 6,
      isPage: 1,
    }).then((res: any) => {
      setNewsList(
        res.vos.map((item) => ({
          ...item,
          shipImage: process.env.TARO_APP_API + item.shipImage,
        }))
      );
    });
  };

  const getBrands = () => {
    requestPOST("index/cooperativePartner").then((res: any) => {
      setBrands(
        res.map((item) => ({
          ...item,
          image: process.env.TARO_APP_API + item.image,
        }))
      );
    });
  };

  const gotoNews = ({ shipUrl }) => {
    let id = new URLSearchParams(shipUrl).get("id");
    Taro.navigateTo({ url: "/packages/productView/index?id=" + id });
    // Taro.navigateTo({
    //   url: `/packages/news/index?id=${id}&ids=${newsList
    //     .map((item) => item.id)
    //     .join(",")}`,
    // });
  };

  const viewDetail = ({ typeId, title, id }) => {
    if (isHomeShow && businessId) {
      Taro.navigateTo({
        url: `/packages/goodsDetail/index?id=${id}`,
      });
    } else {
      Taro.navigateTo({
        url: `/packages/productView/index?id=${typeId}&title=${title}`,
      });
    }
  };

  const gotoGoodsDetail = (id) => {
    Taro.navigateTo({
      url: `/packages/goodsDetail/index?id=${id}`,
    });
  };

  useEffect(() => {
    const token = Taro.getStorageSync("token");
    const userInfo = Taro.getStorageSync("userInfo");
    if (!token || userInfo?.userType != 2) {
      initBannerList();
      getHotProductList();
      getNewProductList();
      getBannerImage();
      getRecommendList();
      getNewsList();
      getBrands();
    }
  }, []);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      return;
    }
    initBannerList();
    getHotProductList();
    getNewProductList();
    getBannerImage();
    getRecommendList();
    getNewsList();
    getBrands();
  }, [isHomeShow]);

  useDidShow(() => {
    const userInfo = Taro.getStorageSync("userInfo");

    if (userInfo.token && !(userInfoRedux as any)?.token) {
      dispatch(setUserInfo(userInfo));
      if (!shopInfo.businessId && userInfo.userType === 2) {
        getShopInfo();
      }
    }
  });

  const getShopInfo = () => {
    requestPOST("shop/shopMyInfo").then((res: any) => {
      dispatch(setShopInfo(res));
      getBuinesCategoryList(res.businessId);
      requestPOST(`other/businessIntroduction/${res.businessId}`).then(
        (res1: any) => {
          requestPOST(`other/businessAppraiseList/${res.businessId}`, {
            businessId: res.businessId,
            isPage: 1,
            pageNum: 1,
            pageSize: 5,
            pageTotal: 0,
          }).then((res2: any) => {
            dispatch(
              setBusinessInfo({
                id: res.businessId,
                info: { ...res, ...res1, ...res2 },
              })
            );
            dispatch(setHomeShow(true));
          });
        }
      );
    });
  };

  const getBuinesCategoryList = (businessId) => {
    requestPOST(`shop/shopCategoryList/${businessId}`).then((res: any) => {
      let nav = [
        { categoryName: "Home", id: 1 },
        { categoryName: "Company Overview", id: 2 },
        { categoryName: "Ratings & Reviews", id: 5 },
        { categoryName: "Feedback", id: 3 },
        { categoryName: "ContactUs", id: 4 },
        ...res,
      ];
      dispatch(setBusinessCategory(nav));
    });
  };

  const [scrollTop, setScrollTop] = useState(0);

  const onClick = () => {
    setScrollTop(0);
    setTimeout(() => {
      setScrollTop(Math.random());
    }, 1);
  };

  return (
    <ScrollView
      className="taroContainer"
      enable-passive={true}
      scroll-y={true}
      scrollWithAnimation
      scrollTop={scrollTop}
    >
      <FloatingBubble
        className="taroify-floating-bubble1"
        icon={<ArrowUp />}
        onClick={onClick}
        axis="lock"
      />
      <HeaderSearch />
      <Header isHome={true} />
      {(!businessId || !isHomeShow) && (
        <View style={{ height: "132px" }}>
          <Swiper autoplay={4000} lazyRender>
            <Swiper.Indicator />
            {swiperList.map((item, index) => (
              <Swiper.Item key={index}>
                <Image
                  src={item.image}
                  width="100%"
                  height={132}
                  mode="aspectFill"
                />
              </Swiper.Item>
            ))}
          </Swiper>
        </View>
      )}
      {/* Popular Products */}
      <View>
        <GoodsTitle
          title="Popular Products 🔥"
          handleMore={() => {
            if (businessId) {
              Taro.switchTab({ url: "/pages/classify/index" });
              dispatch(setActive(1));
            } else {
              Taro.navigateTo({ url: "/packages/productView/index" });
            }
          }}
        />
        <View className={StyleModule.popular}>
          {hotProductList[0] ? (
            <View
              onClick={() => gotoGoodsDetail(hotProductList[0].id)}
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemOne,
              ].join(" ")}
            >
              <Image
                src={hotProductList[0].image}
                width="100%"
                height={100}
                mode="aspectFill"
              />
              <View style={{ padding: "0 10px" }}>
                <View style={{ height: "110px", overflow: "hidden" }}>
                  {hotProductList[0].commodityName}
                </View>
              </View>
              <View style={{ padding: "0 10px" }}>
                Sell: {hotProductList[0].sellNumber || "--"}
              </View>
              <View style={{ padding: "0 10px" }}>
                Min.order: {hotProductList[0].minNum}
              </View>
              <View
                style={{ paddingRight: "10px" }}
                className={StyleModule.price}
              >
                ${hotProductList[0].presentPrice}
              </View>
            </View>
          ) : (
            <View
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemOne,
              ].join(" ")}
            >
              <View style={{ width: "100px", height: "100px" }}></View>
              <View style={{ padding: "0 10px" }}>
                <View>Fine Ceramics</View>
              </View>

              <View
                style={{
                  padding: "0 10px",
                  textDecoration: "line-through",
                  color: "#aaa",
                }}
              >
                $2800.00
              </View>
              <View
                style={{ paddingRight: "10px" }}
                className={StyleModule.price}
              >
                $200.00
              </View>
            </View>
          )}

          {hotProductList[1] ? (
            <View
              onClick={() => gotoGoodsDetail(hotProductList[1].id)}
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemTwo,
              ].join(" ")}
            >
              <View style={{ flex: "0 0 66px" }}>
                <Image
                  src={hotProductList[1].image}
                  width={66}
                  height={144}
                  mode="aspectFill"
                />
              </View>
              <View className={StyleModule.box}>
                <View style={{ height: "37px", overflow: "hidden" }}>
                  {hotProductList[1].commodityName}
                </View>
                <View>Sell: {hotProductList[1].sellNumber || "--"} </View>
                <View>Min.order:{hotProductList[1].minNum} </View>
                <View className={StyleModule.price}>
                  ${hotProductList[1].presentPrice}
                </View>
              </View>
            </View>
          ) : (
            <View
              onClick={() => gotoGoodsDetail(hotProductList[1].id)}
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemTwo,
              ].join(" ")}
            >
              <View style={{ flex: "0 0 66px", height: "70px" }}></View>
              <View className={StyleModule.box}>
                <View style={{ height: "37px", overflow: "hidden" }}>
                  Fine Ceramics
                </View>
                <View
                  style={{
                    textDecoration: "line-through",
                    color: "#aaa",
                  }}
                >
                  $2800.00
                </View>
                <View className={StyleModule.price}>$200.00</View>
              </View>
            </View>
          )}
          {hotProductList[2] ? (
            <View
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemTwo,
              ].join(" ")}
            >
              <View style={{ flex: "0 0 66px" }}>
                <Image
                  src={hotProductList[2].image}
                  width={66}
                  height={144}
                  mode="aspectFill"
                />
              </View>
              <View className={StyleModule.box}>
                <View style={{ height: "37px", overflow: "hidden" }}>
                  {hotProductList[2].commodityName}
                </View>
                <View>Sell: {hotProductList[2].sellNumber || "--"} </View>
                <View>Min.order:{hotProductList[2].minNum} </View>
                <View className={StyleModule.price}>
                  ${hotProductList[2].presentPrice}
                </View>
              </View>
            </View>
          ) : (
            <View
              className={[
                StyleModule.popularItem,
                StyleModule.popularItemTwo,
              ].join(" ")}
            >
              <View style={{ flex: "0 0 66px", height: "70px" }}></View>
              <View className={StyleModule.box}>
                <View style={{ height: "37px", overflow: "hidden" }}>
                  Fine Ceramics
                </View>
                <View
                  style={{
                    textDecoration: "line-through",
                    color: "#aaa",
                  }}
                >
                  $2800.00
                </View>
                <View className={StyleModule.price}>$200.00</View>
              </View>
            </View>
          )}
        </View>
      </View>

      {/* New Products */}
      <View>
        {newProductList.length ? (
          <GoodsTitle
            title="New Products"
            handleMore={() => {
              if (businessId) {
                Taro.switchTab({ url: "/pages/classify/index" });
                dispatch(setActive(1));
              } else {
                Taro.navigateTo({ url: "/packages/productView/index" });
              }
            }}
          />
        ) : (
          ""
        )}
        <View className={StyleModule.productsBox}>
          {newProductList.map((item, index) => (
            <View
              key={index}
              className={StyleModule.productsItem}
              onClick={() => gotoGoodsDetail(item.id)}
            >
              <Image
                src={item.image}
                width="100%"
                height={150}
                mode="aspectFill"
              />
              <View className={StyleModule.info}>
                <View className={StyleModule.text}>{item.commodityName}</View>
                <View>Min.order: {item.minNum}</View>
                <View className={StyleModule.price}>${item.presentPrice}</View>
              </View>
            </View>
          ))}
        </View>
      </View>

      {(!businessId || !isHomeShow) && (
        <View>
          <Image src={bannerImage} width="100%" height={80} mode="aspectFit" />
        </View>
      )}

      {/* Local characteristic product industry */}
      <View>
        {recommendList.length ? (
          <GoodsTitle
            title="Local characteristic product industry"
            handleMore={() => {
              if (businessId) {
                Taro.switchTab({ url: "/pages/classify/index" });
                dispatch(setActive(1));
              } else {
                Taro.navigateTo({ url: "/packages/productView/index" });
              }
            }}
          />
        ) : (
          ""
        )}
        <View className={StyleModule.industry}>
          {recommendList.map((item, index) => (
            <View key={index} className={StyleModule.industryItem}>
              <View style={{ width: "127px" }}>
                <Image
                  src={item.image}
                  width={127}
                  height={127}
                  mode="aspectFill"
                />
              </View>
              <View className={StyleModule.info}>
                <View className={StyleModule.desc1}>
                  {item.title || item.commodityTitle}
                </View>
                <View className={StyleModule.desc}>
                  {item.content || item.commodityName}
                </View>
                <Button
                  onClick={() => viewDetail(item)}
                  color="primary"
                  size="small"
                  style={{ width: "140px" }}
                >
                  View details
                </Button>
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* Want to get quotations */}
      {(!businessId || !isHomeShow) && (
        <View>
          <GoodsTitle title="Want to get quotations" isMore={false} />
          <Quotation />
        </View>
      )}

      {/* News And Trends */}
      {(!businessId || !isHomeShow) && (
        <View>
          <GoodsTitle
            title="Ready to ship"
            handleMore={() => {
              Taro.navigateTo({ url: "/packages/productView/index" });
            }}
          />
          <View className={StyleModule.trends}>
            {newsList.map((item, index) => (
              <View
                key={index}
                className={StyleModule.trendsItem}
                onClick={() => gotoNews(item)}
              >
                <View style={{ flex: "0 0 125px" }}>
                  <Image
                    src={item.shipImage}
                    width={125}
                    height="100%"
                    mode="widthFix"
                  />
                </View>
                <View className={StyleModule.info}>
                  <View className={StyleModule.text}>{item.shipTitle}</View>
                  <View>Location:{item.shipRegion}</View>
                </View>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Co-brands */}
      {(!businessId || !isHomeShow) && (
        <View>
          <GoodsTitle title="Co-brands" isMore={false} />
          <View
            style={{
              padding: "14px",
              display: "flex",
              flexWrap: "wrap",
              gap: "5px",
            }}
          >
            {brands.map((item, index) => (
              <Image key={index} src={item.image} width={81} height={31} />
            ))}
          </View>
        </View>
      )}

      {(!businessId || !isHomeShow) && <HomeFooter />}
      <Footer />
    </ScrollView>
  );
}
